<template>
  <div style="margin: 0; padding: 0">
    <el-container>
      <!-- 页面表头设计 -->
      <el-header style="height: 42px; display: flex; align-items: center; justify-content: space-between; background-color: #409EFF;">
        <span class="center-text" style="color: white; font-size: 18px;">加班监控系统</span>
        <el-popover
            placement="top-start"
            title="用户信息"
            width="200"
            trigger="hover">
          <div style="margin-top: 10px">Name：{{ useName }}</div>
          <div style="margin-top: 10px">ID: {{ useId }}</div>
          <div style="margin-top: 10px" @click="logOut"><el-link>退出</el-link></div>
          <div class="headMain" slot="reference">{{ useName }}</div>
        </el-popover>
      </el-header>

      <el-container>
        <el-aside class="el-aside" width="200px" style="height: auto; min-height: 100vh;">
          <el-button
              class="aside-button"
              :style="{
                backgroundColor: activeButton === 1 ? 'blue' : '',
                color: activeButton === 1 ? 'white' : ''
              }"
              @click="buttonMainSelect(1)">
            加班记录查看
          </el-button>
          <el-button
              class="aside-button"
              :style="{
                backgroundColor: activeButton === 2 ? 'blue' : '',
                color: activeButton === 2 ? 'white' : ''
              }"
              @click="buttonMainSelect(2)">
            加班记录管理
          </el-button>
          <el-button
              class="aside-button"
              :style="{
                backgroundColor: activeButton === 3 ? 'blue' : '',
                color: activeButton === 3 ? 'white' : ''
              }"
              @click="buttonMainSelect(3)">
            加班统计
          </el-button>
          <!-- 新增加班排名分析按钮 -->
          <el-button
              class="aside-button"
              :style="{
                backgroundColor: activeButton === 4 ? 'blue' : '',
                color: activeButton === 4 ? 'white' : ''
              }"
              @click="buttonMainSelect(4)">
            加班排名分析
          </el-button>
        </el-aside>

        <el-container>
          <!-- 主题设计 -->
          <el-main class="el-main" style="height: calc(100vh - 105px); overflow: auto">
            <!-- 加班记录查看 -->
            <div v-if="buttonDoe === 1">
              <!-- 分页控件 -->
              <el-row style="margin-bottom: 20px;">
                <el-col :span="24" style="text-align: right;">
                  <el-pagination
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="currentPage"
                      :page-sizes="[50, 100, 200, 500]"
                      :page-size="pageSize"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="totalRecords">
                  </el-pagination>
                </el-col>
              </el-row>

              <el-table :data="overtimeData" style="width: 100%" border v-loading="loading">
                <el-table-column prop="employeeNumber" label="工号" width="120" sortable></el-table-column>
                <el-table-column prop="name" label="姓名" width="120" sortable></el-table-column>
                <el-table-column prop="department" label="部门" width="120" sortable></el-table-column>
                <el-table-column prop="section" label="科室" width="120" sortable></el-table-column>
                <el-table-column prop="overtimeDate" label="加班日期" width="120" sortable></el-table-column>
                <el-table-column prop="overtimeHour" label="加班时长(小时)" width="120"></el-table-column>
                <el-table-column prop="operation" label="操作类型" width="120"></el-table-column>
                <el-table-column prop="category" label="加班类别" width="120"></el-table-column>
                <el-table-column prop="reason" label="加班原因" width="180"></el-table-column>
              </el-table>

              <!-- 底部分页控件 -->
              <el-row style="margin-top: 20px;">
                <el-col :span="24" style="text-align: right;">
                  <el-pagination
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="currentPage"
                      :page-sizes="[50, 100, 200, 500]"
                      :page-size="pageSize"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="totalRecords">
                  </el-pagination>
                </el-col>
              </el-row>
            </div>

            <!-- 加班记录管理 -->
            <div v-if="buttonDoe === 2">
              <el-row :gutter="20" style="margin-bottom: 20px;">
                <el-col :span="8">
                  <el-button
                      type="primary"
                      @click="openOvertimeDialog(1, null)"
                      style="margin-bottom: 20px;"
                      v-if="useName === '刘浩'"
                  >
                    添加加班记录
                  </el-button>

                  <!-- 上传Excel按钮 -->
                  <el-button
                      type="success"
                      @click="openExcelUploadDialog"
                      style="margin-bottom: 20px; margin-left: 10px;"
                      v-if="useName === '刘浩'"
                  >
                    上传Excel文档
                  </el-button>

                  <!-- 导出数据按钮 -->
                  <el-button
                      type="warning"
                      @click="exportAllData"
                      style="margin-bottom: 20px; margin-left: 10px;"
                  >
                    导出全部数据
                  </el-button>
                </el-col>
                <el-col :span="16" style="text-align: right;">
                  <el-button
                      type="text"
                      @click="downloadExcelTemplate"
                      style="margin-bottom: 20px;"
                  >
                    下载Excel模板
                  </el-button>
                </el-col>
              </el-row>

              <el-table :data="filteredOvertimeData" style="width: 100%" border>
                <el-table-column prop="employeeNumber" label="工号" width="120" sortable></el-table-column>
                <el-table-column prop="name" label="姓名" width="120" sortable></el-table-column>
                <el-table-column prop="department" label="部门" width="120" sortable></el-table-column>
                <el-table-column prop="section" label="科室" width="120" sortable></el-table-column>
                <el-table-column prop="overtimeDate" label="加班日期" width="120" sortable></el-table-column>
                <el-table-column prop="overtimeHour" label="加班时长(小时)" width="120"></el-table-column>
                <el-table-column prop="operation" label="操作类型" width="120"></el-table-column>
                <el-table-column prop="category" label="加班类别" width="120"></el-table-column>
                <el-table-column prop="reason" label="加班原因" width="180"></el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                        size="mini"
                        @click="openOvertimeDialog(2, scope)"
                        v-if="useName === '刘浩' || scope.row.process_status === useName"
                    >编辑</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 加班统计 -->
            <div v-if="buttonDoe === 3">
              <el-row :gutter="20" style="margin-bottom: 20px;">
                <el-col :span="8">
                  <el-select v-model="selectedYear" placeholder="选择年份" @change="calculateOvertimeStats">
                    <el-option
                        v-for="year in availableYears"
                        :key="year"
                        :label="year + '年'"
                        :value="year">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <el-select v-model="selectedMonth" placeholder="选择月份" @change="calculateOvertimeStats">
                    <el-option
                        v-for="month in 12"
                        :key="month"
                        :label="month + '月'"
                        :value="month">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="8" style="text-align: right;">
                  <el-button type="primary" @click="exportOvertimeStats">
                    导出统计Excel
                  </el-button>
                </el-col>
              </el-row>

              <el-table :data="overtimeStatsData" style="width: 100%" border>
                <el-table-column prop="employeeNumber" label="工号" width="120" fixed="left"></el-table-column>
                <el-table-column prop="name" label="姓名" width="120" fixed="left"></el-table-column>
                <el-table-column prop="department" label="部门" width="120"></el-table-column>
                <el-table-column prop="section" label="科室" width="120"></el-table-column>
                <el-table-column prop="totalHours" label="总加班时长(小时)" width="140" sortable></el-table-column>
                <el-table-column prop="avgHours" label="平均加班时长(小时)" width="140" sortable></el-table-column>
                <el-table-column prop="count" label="加班次数" width="100" sortable></el-table-column>
              </el-table>
            </div>

            <!-- 加班排名分析 -->
            <div v-if="buttonDoe === 4">
              <!-- 面包屑导航 -->
              <el-breadcrumb separator=">" style="margin-bottom: 20px;">
                <el-breadcrumb-item>
                  <el-button type="text" @click="drillToLevel(0)">个人加班排名</el-button>
                </el-breadcrumb-item>
                <el-breadcrumb-item v-if="drillLevel >= 1">
                  <el-button type="text" @click="drillToLevel(1)">
                    {{ currentEmployeeName }} - 加班类别
                  </el-button>
                </el-breadcrumb-item>
                <el-breadcrumb-item v-if="drillLevel >= 2">
                  <span>{{ currentCategory }} - 加班原因</span>
                </el-breadcrumb-item>
              </el-breadcrumb>

              <!-- 筛选条件 -->
              <el-row :gutter="20" style="margin-bottom: 20px;">
                <el-col :span="6">
                  <el-select v-model="rankYear" placeholder="选择年份" @change="calculateRanking">
                    <el-option
                        v-for="year in availableYears"
                        :key="year"
                        :label="year + '年'"
                        :value="year">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-select v-model="rankMonth" placeholder="选择月份" @change="calculateRanking" clearable>
                    <el-option
                        v-for="month in 12"
                        :key="month"
                        :label="month + '月'"
                        :value="month">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-select v-model="rankDepartment" placeholder="选择部门" @change="calculateRanking" clearable>
                    <el-option
                        v-for="dept in departments"
                        :key="dept"
                        :label="dept"
                        :value="dept">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="6" style="text-align: right;">
                  <el-button type="primary" @click="exportRankingData">
                    导出分析数据
                  </el-button>
                </el-col>
              </el-row>

              <!-- 第一级：个人加班排名柱状图 -->
              <div v-if="drillLevel === 0" class="chart-container">
                <div ref="rankingChart" style="width: 100%; height: 500px;"></div>
              </div>

              <!-- 第二级：加班类别分析 -->
              <div v-if="drillLevel === 1" class="chart-container">
                <h3>{{ currentEmployeeName }} - 加班类别分布</h3>
                <div ref="categoryChart" style="width: 100%; height: 400px;"></div>

                <!-- 类别详情表格 -->
                <el-table :data="categoryDetailData" style="width: 100%; margin-top: 20px;" border>
                  <el-table-column prop="category" label="加班类别" width="150"></el-table-column>
                  <el-table-column prop="totalHours" label="总时长(小时)" width="120" sortable></el-table-column>
                  <el-table-column prop="count" label="加班次数" width="100" sortable></el-table-column>
                  <el-table-column prop="avgHours" label="平均时长(小时)" width="120" sortable></el-table-column>
                  <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button type="text" @click="drillToReason(scope.row.category)">
                        查看原因
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <!-- 第三级：加班原因详情 -->
              <div v-if="drillLevel === 2" class="chart-container">
                <h3>{{ currentEmployeeName }} - {{ currentCategory }} - 加班原因</h3>

                <!-- 原因统计图表 -->
                <div ref="reasonChart" style="width: 100%; height: 300px;"></div>

                <!-- 原因详情表格 -->
                <el-table :data="reasonDetailData" style="width: 100%; margin-top: 20px;" border>
                  <el-table-column prop="overtimeDate" label="加班日期" width="120" sortable></el-table-column>
                  <el-table-column prop="overtimeHour" label="加班时长(小时)" width="120" sortable></el-table-column>
                  <el-table-column prop="reason" label="加班原因"></el-table-column>
                  <el-table-column prop="department" label="部门" width="120"></el-table-column>
                  <el-table-column prop="section" label="科室" width="120"></el-table-column>
                </el-table>
              </div>
            </div>
          </el-main>
        </el-container>
      </el-container>
    </el-container>

    <!-- 加班记录弹窗 -->
    <el-dialog
        :title="overtimeDoe === 1 ? '添加加班记录' : '编辑加班记录'"
        :visible.sync="overtimeDialogVisible"
        width="50%">
      <el-form label-width="140px" :model="overtimeForm" :rules="overtimeRules" ref="overtimeForm">
        <el-form-item label="工号" prop="employeeNumber">
          <el-input v-model="overtimeForm.employeeNumber" :disabled="overtimeDoe === 2"></el-input>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="overtimeForm.name" :disabled="overtimeDoe === 2"></el-input>
        </el-form-item>

        <el-form-item label="部门" prop="department">
          <el-input v-model="overtimeForm.department"></el-input>
        </el-form-item>

        <el-form-item label="科室" prop="section">
          <el-input v-model="overtimeForm.section"></el-input>
        </el-form-item>

        <el-form-item label="加班日期" prop="overtimeDate">
          <el-date-picker
              v-model="overtimeForm.overtimeDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              style="width: 100%">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="加班时长(小时)" prop="overtimeHour">
          <el-input-number
              v-model="overtimeForm.overtimeHour"
              :min="0.5"
              :max="24"
              :step="0.5"
              style="width: 100%">
          </el-input-number>
        </el-form-item>

        <el-form-item label="操作类型" prop="operation">
          <el-select v-model="overtimeForm.operation" placeholder="请选择操作类型" style="width: 100%">
            <el-option label="新增" value="新增"></el-option>
            <el-option label="修改" value="修改"></el-option>
            <el-option label="删除" value="删除"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="加班类别" prop="category">
          <el-select v-model="overtimeForm.category" placeholder="请选择加班类别" style="width: 100%">
            <el-option label="工作日加班" value="工作日加班"></el-option>
            <el-option label="周末加班" value="周末加班"></el-option>
            <el-option label="节假日加班" value="节假日加班"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="加班原因" prop="reason">
          <el-input
              type="textarea"
              :rows="3"
              v-model="overtimeForm.reason"
              placeholder="请输入加班原因">
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="overtimeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitOvertimeForm">确定</el-button>
      </span>
    </el-dialog>

    <!-- Excel上传对话框 -->
    <el-dialog
        title="上传Excel文档"
        :visible.sync="excelUploadDialogVisible"
        width="40%">
      <div class="upload-area" @click="$refs.upload.click()">
        <div v-if="!selectedFile">
          <i class="el-icon-upload upload-icon"></i>
          <div>点击或拖拽文件到此处上传</div>
          <div class="el-upload__text">支持Excel文件，大小不超过10MB</div>
        </div>
        <div v-else>
          <div>已选择文件: {{ selectedFile.name }}</div>
          <el-button
              type="text"
              @click.stop="selectedFile = null; $refs.upload.value = ''">
            重新选择
          </el-button>
        </div>
        <input
            type="file"
            ref="upload"
            style="display: none"
            accept=".xlsx,.xls"
            @change="handleExcelFileChange">
      </div>

      <div v-if="uploadResult" style="margin-top: 20px;">
        <el-alert
            :title="`导入结果: 成功 ${uploadResult.success} 条, 失败 ${uploadResult.fail} 条`"
            :type="uploadResult.fail > 0 ? 'warning' : 'success'"
            show-icon>
        </el-alert>

        <div v-if="uploadResult.failDetails && uploadResult.failDetails.length > 0"
             style="margin-top: 10px; max-height: 200px; overflow-y: auto;">
          <div style="font-weight: bold; margin-bottom: 5px;">失败详情:</div>
          <el-table
              :data="uploadResult.failDetails"
              size="mini"
              border
              style="width: 100%">
            <el-table-column prop="row" label="行号" width="80"></el-table-column>
            <el-table-column prop="reason" label="失败原因"></el-table-column>
          </el-table>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeExcelUploadDialog">取消</el-button>
        <el-button
            type="primary"
            @click="submitExcelUpload"
            :loading="uploadLoading">
          {{ uploadLoading ? '上传中...' : '开始上传' }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import _ from "lodash";
import * as echarts from 'echarts';

export default {
  name: "OvertimeMonitoring",
  data() {
    return {

      currentPage: 1,
      pageSize: 100,
      totalRecords: 0,
      loading: false,

      useName: '',
      useId: '',
      activeButton: 1,
      buttonDoe: 1,
      drillLevel: 0, // 0: 个人排名, 1: 加班类别, 2: 加班原因
      currentEmployeeName: '',
      currentEmployeeNumber: '',
      currentCategory: '',
      rankYear: new Date().getFullYear(),
      rankMonth: null,
      rankDepartment: null,
      departments: [],

      // 图表实例
      rankingChart: null,
      categoryChart: null,
      reasonChart: null,

      // 分析数据
      rankingData: [],
      categoryDetailData: [],
      reasonDetailData: [],
      // 加班记录数据
      overtimeData: [



      ],
      overtimeDialogVisible: false,
      overtimeDoe: 1, // 1: 添加, 2: 编辑
      overtimeForm: {
        id: '',
        create_time: '',
        update_time: '',
        creator: '',
        process_status: '',
        sys_update_user: '',
        sys_audit_user: '',
        sys_audit_time: '',
        sys_deleted: 0,
        employeeNumber: '',
        name: '',
        department: '',
        section: '',
        overtimeDate: '',
        overtimeHour: '',
        operation: '',
        category: '',
        reason: '',
      },
      overtimeRules: {
        employeeNumber: [
          { required: true, message: '请输入工号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        overtimeDate: [
          { required: true, message: '请选择加班日期', trigger: 'change' }
        ],
        overtimeHour: [
          { required: true, message: '请输入加班时长', trigger: 'blur' },
          { type: 'number', min: 0.5, max: 24, message: '加班时长必须在0.5到24小时之间', trigger: 'blur' }
        ],
        operation: [
          { required: true, message: '请选择操作类型', trigger: 'change' }
        ],
        category: [
          { required: true, message: '请选择加班类别', trigger: 'change' }
        ]
      },

      // Excel上传相关
      excelUploadDialogVisible: false,
      selectedFile: null,
      uploadLoading: false,
      uploadResult: null,

      // 统计相关
      selectedYear: new Date().getFullYear(),
      selectedMonth: new Date().getMonth() + 1,
      availableYears: [2023, 2024, 2025, 2026, 2027],
      overtimeStatsData: []
    };
  },
  computed: {
    filteredOvertimeData() {
      if (this.useName === '刘浩') {
        return this.overtimeData;
      } else {
        return this.overtimeData.filter(item => item.process_status === this.useName);
      }
    }
  },
  created() {
    // 默认显示加班记录查看页面并加载第一页数据
    this.activeButton = 1;
    this.buttonDoe = 1;
    this.currentPage = 1;
    this.pageSize = 100;
    this.inquiry().then(() => {
      this.queryOvertimeByPage();
    });
  },
  mounted() {
    // 初始化图表
    this.$nextTick(() => {
      this.initCharts();
    });
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.rankingChart) {
      this.rankingChart.dispose();
    }
    if (this.categoryChart) {
      this.categoryChart.dispose();
    }
    if (this.reasonChart) {
      this.reasonChart.dispose();
    }
  },
  methods: {

    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1; // 重置到第一页
      this.queryOvertimeByPage();
    },

    // 当前页改变
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.queryOvertimeByPage();
    },

    // 分页查询加班记录
    async queryOvertimeByPage() {
      this.loading = true;
      try {
        const result = await this.$request.post('/queryOvertimeMonitoringByPage', {
          page: this.currentPage,
          pageSize: this.pageSize
        });
        if (result.code === 401) {
          this.$router.push('UserLogin');
          this.$message.error("您未登录，请登录");
        } else {
          this.overtimeData = result.data.list || [];
          this.totalRecords = result.data.total || 0;
        }
      } catch (error) {
        console.error('分页查询加班记录失败:', error);
        this.$message.error('分页查询加班记录失败');
      } finally {
        this.loading = false;
      }
    },

    generateUniqueId() {
      // 使用时间戳+随机数确保唯一性
      const timestamp = new Date().getTime();
      const random = Math.random().toString(36).substring(2, 15);
      return `overtime_${timestamp}_${random}`;
    },

    // 或者在methods中添加一个更复杂的ID生成器
    generateUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },


    initCharts() {
      if (this.$refs.rankingChart) {
        this.rankingChart = echarts.init(this.$refs.rankingChart);
      }
      if (this.$refs.categoryChart) {
        this.categoryChart = echarts.init(this.$refs.categoryChart);
      }
      if (this.$refs.reasonChart) {
        this.reasonChart = echarts.init(this.$refs.reasonChart);
      }
    },

    // 侧边栏按钮切换
    buttonMainSelect(buttonIndex) {
      this.activeButton = buttonIndex;
      this.buttonDoe = buttonIndex;

      if (buttonIndex === 1) {
        // 加班记录查看：使用分页查询
        this.currentPage = 1;
        this.pageSize = 100;
        this.queryOvertimeByPage();
      } else if (buttonIndex === 3) {
        // 加班统计：使用全量数据
        this.calculateOvertimeStats();
      } else if (buttonIndex === 4) {
        // 加班排名分析：使用全量数据
        this.$nextTick(() => {
          this.initCharts();
          this.calculateRanking();
        });
      }
      // 其他模块保持原有逻辑
    },


    // 计算加班排名
    calculateRanking() {
      if (!this.rankYear) {
        this.$message.warning('请选择年份');
        return;
      }

      // 筛选数据
      const filteredData = this.overtimeData.filter(item => {
        if (!item.overtimeDate) return false;

        const date = new Date(item.overtimeDate);
        const yearMatch = date.getFullYear() === this.rankYear;
        const monthMatch = !this.rankMonth || (date.getMonth() + 1 === this.rankMonth);
        const deptMatch = !this.rankDepartment || item.department === this.rankDepartment;

        return yearMatch && monthMatch && deptMatch;
      });

      // 获取部门列表
      this.departments = [...new Set(this.overtimeData.map(item => item.department))].filter(Boolean);

      // 按员工分组统计
      const employeeStats = {};
      filteredData.forEach(item => {
        if (!employeeStats[item.employeeNumber]) {
          employeeStats[item.employeeNumber] = {
            employeeNumber: item.employeeNumber,
            name: item.name,
            department: item.department,
            section: item.section,
            totalHours: 0,
            count: 0,
            categories: {},
            reasons: {}
          };
        }

        const stats = employeeStats[item.employeeNumber];
        stats.totalHours += parseFloat(item.overtimeHour) || 0;
        stats.count += 1;

        // 统计类别
        if (item.category) {
          if (!stats.categories[item.category]) {
            stats.categories[item.category] = {
              totalHours: 0,
              count: 0,
              reasons: {}
            };
          }
          stats.categories[item.category].totalHours += parseFloat(item.overtimeHour) || 0;
          stats.categories[item.category].count += 1;
        }

        // 统计原因
        if (item.reason) {
          if (!stats.reasons[item.reason]) {
            stats.reasons[item.reason] = {
              totalHours: 0,
              count: 0,
              records: []
            };
          }
          stats.reasons[item.reason].totalHours += parseFloat(item.overtimeHour) || 0;
          stats.reasons[item.reason].count += 1;
          stats.reasons[item.reason].records.push(item);
        }
      });

      this.rankingData = Object.values(employeeStats)
          .sort((a, b) => b.totalHours - a.totalHours)
          .slice(0, 20); // 只显示前20名

      this.renderRankingChart();
    },

    // 渲染排名柱状图
    renderRankingChart() {
      if (!this.rankingChart) return;

      const chartData = this.rankingData.map(item => ({
        name: item.name,
        value: item.totalHours,
        employeeNumber: item.employeeNumber
      }));

      const option = {
        title: {
          text: '个人加班时长排名',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            const data = params[0];
            const employee = this.rankingData.find(item => item.name === data.name);
            return `
              ${data.name}<br/>
              部门: ${employee.department}<br/>
              总时长: ${data.value} 小时<br/>
              加班次数: ${employee.count} 次<br/>
              点击查看详情
            `;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '加班时长(小时)'
        },
        yAxis: {
          type: 'category',
          data: chartData.map(item => item.name),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        series: [
          {
            name: '加班时长',
            type: 'bar',
            data: chartData,
            itemStyle: {
              color: function(params) {
                const colorList = [
                  '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae',
                  '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570'
                ];
                return colorList[params.dataIndex % colorList.length];
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      this.rankingChart.setOption(option);

      // 添加点击事件
      this.rankingChart.off('click');
      this.rankingChart.on('click', (params) => {
        const employeeData = this.rankingData.find(item => item.name === params.name);
        this.drillToCategory(employeeData);
      });
    },

    // 钻取到加班类别
    drillToCategory(employeeData) {
      this.drillLevel = 1;
      this.currentEmployeeName = employeeData.name;
      this.currentEmployeeNumber = employeeData.employeeNumber;

      // 准备类别数据
      this.categoryDetailData = Object.entries(employeeData.categories).map(([category, data]) => ({
        category,
        totalHours: parseFloat(data.totalHours.toFixed(2)),
        count: data.count,
        avgHours: parseFloat((data.totalHours / data.count).toFixed(2))
      })).sort((a, b) => b.totalHours - a.totalHours);

      this.renderCategoryChart();
    },

    // 渲染类别图表
    renderCategoryChart() {
      if (!this.categoryChart) return;

      const option = {
        title: {
          text: `${this.currentEmployeeName} - 加班类别分布`,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} 小时 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '加班时长',
            type: 'pie',
            radius: '50%',
            data: this.categoryDetailData.map(item => ({
              name: item.category,
              value: item.totalHours
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      this.categoryChart.setOption(option);
    },

    // 钻取到加班原因
    drillToReason(category) {
      this.drillLevel = 2;
      this.currentCategory = category;

      const employeeData = this.rankingData.find(item =>
          item.employeeNumber === this.currentEmployeeNumber
      );

      if (employeeData && employeeData.categories[category]) {
        // 修复：删除未使用的 categoryData 变量
        // const categoryData = employeeData.categories[category];

        // 准备原因数据
        const reasonStats = {};
        Object.entries(employeeData.reasons).forEach(([reason, data]) => {
          data.records.forEach(record => {
            if (record.category === category) {
              if (!reasonStats[reason]) {
                reasonStats[reason] = {
                  totalHours: 0,
                  count: 0,
                  records: []
                };
              }
              reasonStats[reason].totalHours += parseFloat(record.overtimeHour) || 0;
              reasonStats[reason].count += 1;
              reasonStats[reason].records.push(record);
            }
          });
        });

        // 准备详情表格数据
        this.reasonDetailData = [];
        Object.values(reasonStats).forEach(stats => {
          stats.records.forEach(record => {
            this.reasonDetailData.push({
              overtimeDate: record.overtimeDate,
              overtimeHour: record.overtimeHour,
              reason: record.reason,
              department: record.department,
              section: record.section
            });
          });
        });

        this.reasonDetailData.sort((a, b) => new Date(b.overtimeDate) - new Date(a.overtimeDate));

        this.renderReasonChart(reasonStats);
      }
    },

    // 渲染原因图表
    renderReasonChart(reasonStats) {
      if (!this.reasonChart) return;

      const chartData = Object.entries(reasonStats)
          .map(([reason, data]) => ({
            name: reason.length > 10 ? reason.substring(0, 10) + '...' : reason,
            fullName: reason,
            value: data.totalHours
          }))
          .sort((a, b) => b.value - a.value)
          .slice(0, 10); // 只显示前10个原因

      const option = {
        title: {
          text: `${this.currentEmployeeName} - ${this.currentCategory} - 原因分布`,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            return `${params.data.fullName}<br/>总时长: ${params.value} 小时`;
          }
        },
        xAxis: {
          type: 'category',
          data: chartData.map(item => item.name),
          axisLabel: {
            interval: 0,
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '时长(小时)'
        },
        series: [
          {
            name: '加班时长',
            type: 'bar',
            data: chartData,
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      };

      this.reasonChart.setOption(option);
    },

    // 钻取导航
    drillToLevel(level) {
      this.drillLevel = level;

      if (level === 0) {
        this.currentEmployeeName = '';
        this.currentEmployeeNumber = '';
        this.currentCategory = '';
        this.$nextTick(() => {
          this.renderRankingChart();
        });
      } else if (level === 1) {
        this.currentCategory = '';
        const employeeData = this.rankingData.find(item =>
            item.employeeNumber === this.currentEmployeeNumber
        );
        if (employeeData) {
          this.$nextTick(() => {
            this.renderCategoryChart();
          });
        }
      }
    },

    // 导出分析数据
    exportRankingData() {
      let dataToExport = [];
      let filename = '';

      if (this.drillLevel === 0) {
        // 导出排名数据
        dataToExport = this.rankingData.map(item => ({
          工号: item.employeeNumber,
          姓名: item.name,
          部门: item.department,
          科室: item.section,
          总加班时长: item.totalHours,
          加班次数: item.count,
          平均时长: parseFloat((item.totalHours / item.count).toFixed(2))
        }));
        filename = `加班排名_${this.rankYear}年${this.rankMonth ? this.rankMonth + '月' : ''}.xlsx`;
      } else if (this.drillLevel === 1) {
        // 导出类别数据
        dataToExport = this.categoryDetailData;
        filename = `${this.currentEmployeeName}_加班类别分析.xlsx`;
      } else if (this.drillLevel === 2) {
        // 导出原因数据
        dataToExport = this.reasonDetailData;
        filename = `${this.currentEmployeeName}_${this.currentCategory}_加班原因.xlsx`;
      }

      if (dataToExport.length === 0) {
        this.$message.warning('没有数据可导出');
        return;
      }

      try {
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet(dataToExport);
        XLSX.utils.book_append_sheet(wb, ws, '分析数据');
        XLSX.writeFile(wb, filename);
        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败');
      }
    },

    inquiry() {
      return new Promise((resolve, reject) => {
        const useId = localStorage.getItem('userName')?.replace(/"/g, '') || '';
        if (!useId) {
          this.$router.push('UserLogin');
          this.$message.error("您未登录，请登录");
          reject(new Error("未登录"));
          return;
        }

        this.$request.post('/useQueryPower', {
          queryFiledName: 'goodProductCondition',
          userId: useId,
        }).then(result => {
          if (result.code === 401) {
            this.$router.push('UserLogin');
            this.$message.error("您未登录，请登录");
            reject(new Error("未登录"));
          } else {
            this.useName = result.data.name;
            this.useId = useId;
            resolve();
          }
        }).catch(error => {
          console.error('初始化查询失败:', error);
          this.$message.error("初始化查询失败");
          reject(error);
        });
      });
    },

    // 查询所有加班记录
    async queryAllOvertime() {
      try {
        const result = await this.$request.post('/queryOvertimeMonitoring');
        if (result.code === 401) {
          this.$router.push('UserLogin');
          this.$message.error("您未登录，请登录");
        } else {
          this.overtimeData = result.data || [];
        }
      } catch (error) {
        console.error('查询加班记录失败:', error);
        this.$message.error('查询加班记录失败');
      }
    },

    // 打开加班记录对话框
    openOvertimeDialog(doe, scope) {
      this.overtimeDoe = doe;

      if (doe === 1) { // 添加
        this.overtimeForm = {
          id: '',
          create_time: '',
          update_time: '',
          creator: this.useName,
          process_status: '',
          sys_update_user: this.useName,
          sys_audit_user: '',
          sys_audit_time: '',
          sys_deleted: 0,
          employeeNumber: '',
          name: '',
          department: '',
          section: '',
          overtimeDate: '',
          overtimeHour: 0,
          operation: '',
          category: '',
          reason: ''
        };
      } else if (doe === 2) { // 编辑
        this.overtimeForm = _.cloneDeep(scope.row);
      }

      this.overtimeDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.overtimeForm.clearValidate();
      });
    },

    // 提交加班记录表单
    async submitOvertimeForm() {
      this.$refs.overtimeForm.validate(async valid => {
        if (!valid) return;

        try {
          let result;
          const formData = {
            ...this.overtimeForm,
            update_time: new Date().toISOString(),
            sys_update_user: this.useName
          };

          if (this.overtimeDoe === 1) { // 添加
            formData.create_time = new Date().toISOString();
            formData.creator = this.useName;
            result = await this.$request.post('/insertOvertimeMonitoring', formData);
          } else { // 编辑
            result = await this.$request.post('/editOvertimeMonitoring', formData);
          }

          if (result.code === 401) {
            this.$router.push('UserLogin');
            this.$message.error("您未登录，请登录");
          } else if (result.code === 200 || result.msg === 'success') {
            this.$message.success(this.overtimeDoe === 1 ? "添加成功" : "更新成功");
            this.overtimeDialogVisible = false;

            // 根据当前所在模块重新加载数据
            if (this.buttonDoe === 1) {
              // 如果在加班记录查看页面，重新查询当前页
              await this.queryOvertimeByPage();
            } else {
              // 其他页面重新查询全部数据
              await this.queryAllOvertime();
            }
          } else {
            this.$message.error(result.msg || (this.overtimeDoe === 1 ? "添加失败" : "更新失败"));
          }
        } catch (error) {
          console.error('操作失败:', error);
          this.$message.error(this.overtimeDoe === 1 ? "添加失败" : "更新失败");
        }
      });
    },

    // 用户退出
    logOut() {
      localStorage.removeItem('userName');
      this.$router.push('UserLogin');
      this.$message.success("已退出登录");
    },

    // 计算加班统计
    calculateOvertimeStats() {
      if (!this.selectedYear || !this.selectedMonth) {
        this.$message.warning('请选择年份和月份');
        return;
      }

      // 筛选指定年月的数据
      const filteredData = this.overtimeData.filter(item => {
        if (!item.overtimeDate) return false;
        const date = new Date(item.overtimeDate);
        return date.getFullYear() === this.selectedYear &&
            date.getMonth() + 1 === this.selectedMonth;
      });

      // 按员工分组统计
      const stats = {};
      filteredData.forEach(item => {
        if (!stats[item.employeeNumber]) {
          stats[item.employeeNumber] = {
            employeeNumber: item.employeeNumber,
            name: item.name,
            department: item.department,
            section: item.section,
            totalHours: 0,
            count: 0
          };
        }
        stats[item.employeeNumber].totalHours += parseFloat(item.overtimeHour) || 0;
        stats[item.employeeNumber].count += 1;
      });

      // 计算平均值
      this.overtimeStatsData = Object.values(stats).map(item => ({
        ...item,
        avgHours: (item.totalHours / item.count).toFixed(2)
      }));
    },

    // 导出统计数据
    exportOvertimeStats() {
      if (!this.overtimeStatsData.length) {
        this.$message.warning('没有数据可导出');
        return;
      }

      try {
        const wb = XLSX.utils.book_new();

        // 准备表头
        const headers = [
          '工号', '姓名', '部门', '科室', '总加班时长(小时)', '平均加班时长(小时)', '加班次数'
        ];

        // 准备数据
        const excelData = [headers];
        this.overtimeStatsData.forEach(item => {
          excelData.push([
            item.employeeNumber,
            item.name,
            item.department,
            item.section,
            item.totalHours,
            item.avgHours,
            item.count
          ]);
        });

        const ws = XLSX.utils.aoa_to_sheet(excelData);
        XLSX.utils.book_append_sheet(wb, ws, '加班统计');

        const filename = `${this.selectedYear}年${this.selectedMonth}月加班统计.xlsx`;
        XLSX.writeFile(wb, filename);

        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出Excel失败:', error);
        this.$message.error('导出失败');
      }
    },

    // 导出全部数据
    async exportAllData() {
      if (!this.overtimeData || this.overtimeData.length === 0) {
        this.$message.warning('没有数据可导出');
        return;
      }

      try {
        const wb = XLSX.utils.book_new();

        // 准备表头
        const headers = [
          '工号', '姓名', '部门', '科室', '加班日期', '加班时长(小时)',
          '操作类型', '加班类别', '加班原因', '创建时间', '更新时间',
          '创建人', '处理状态', '系统更新用户', '系统审核用户',
          '系统审核时间', '系统删除标记'
        ];

        // 准备数据
        const excelData = [headers];
        this.overtimeData.forEach(item => {
          excelData.push([
            item.employeeNumber,
            item.name,
            item.department,
            item.section,
            item.overtimeDate,
            item.overtimeHour,
            item.operation,
            item.category,
            item.reason,
            item.create_time,
            item.update_time,
            item.creator,
            item.process_status,
            item.sys_update_user,
            item.sys_audit_user,
            item.sys_audit_time,
            item.sys_deleted
          ]);
        });

        const ws = XLSX.utils.aoa_to_sheet(excelData);
        XLSX.utils.book_append_sheet(wb, ws, '全部加班记录');

        // 生成文件名
        const now = new Date();
        const timestamp = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
        const filename = `全部加班记录_${timestamp}.xlsx`;

        XLSX.writeFile(wb, filename);

        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出Excel失败:', error);
        this.$message.error('导出失败');
      }
    },

    // 下载Excel模板
    downloadExcelTemplate() {
      try {
        const wb = XLSX.utils.book_new();

        // 示例数据
        const exampleData = [
          ['工号', '姓名', '部门', '科室', '加班日期', '加班时长(小时)', '操作类型', '加班类别', '加班原因'],
          ['GW00109612', '李亚男', '品质技术部', '产品技术科', '2025-11-01', 3, '生产', '工作日加班', '装配生产线生产'],
          ['GW0800717', '邹永林', '制造部', '', '2025-11-02', 8, '生产', '周末加班', '设备调试'],
          ['GW0800611', '李勇', '品质技术部', '', '2025-11-01', 8, '其他', '节假日加班', '公司值班']
        ];

        const ws = XLSX.utils.aoa_to_sheet(exampleData);
        XLSX.utils.book_append_sheet(wb, ws, '加班记录模板');

        // 添加说明
        const notes = [
          ['填写说明：'],
          ['1. 第一行为表头，请勿修改表头名称'],
          ['2. 带*号为必填项，实际使用中不需要加*号'],
          ['3. 加班日期格式：YYYY-MM-DD（如：2025-11-01）'],
          ['4. 加班时长单位：小时，支持小数（如：3.5）'],
          ['5. 操作类型：新增/修改/删除/生产/其他'],
          ['6. 加班类别：工作日加班/周末加班/节假日加班'],
          ['7. 请确保工号、姓名、加班日期、加班时长不为空']
        ];
        const notesSheet = XLSX.utils.aoa_to_sheet(notes);
        XLSX.utils.book_append_sheet(wb, notesSheet, '填写说明');

        XLSX.writeFile(wb, '加班记录导入模板.xlsx');
        this.$message.success('模板下载成功');
      } catch (error) {
        console.error('下载模板失败:', error);
        this.$message.error('下载模板失败');
      }
    },

    // Excel上传相关方法
    openExcelUploadDialog() {
      this.excelUploadDialogVisible = true;
      this.selectedFile = null;
      this.uploadResult = null;
      this.$nextTick(() => {
        if (this.$refs.upload) {
          this.$refs.upload.value = '';
        }
      });
    },

    closeExcelUploadDialog() {
      this.excelUploadDialogVisible = false;
      this.selectedFile = null;
      this.uploadResult = null;
    },

    handleExcelFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      const isValidType = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].includes(file.type);
      if (!isValidType) {
        this.$message.error('请上传有效的Excel文件(.xlsx或.xls)');
        this.$refs.upload.value = '';
        return;
      }

      if (file.size > 10 * 1024 * 1024) {
        this.$message.error('文件大小不能超过10MB');
        this.$refs.upload.value = '';
        return;
      }

      this.selectedFile = file;
    },

    async submitExcelUpload() {
      if (!this.selectedFile) {
        this.$message.warning('请选择要上传的Excel文件');
        return;
      }

      this.uploadLoading = true;

      try {
        const data = await this.readExcelFile(this.selectedFile);
        const overtimeData = this.transformExcelData(data);

        let successCount = 0;
        let failCount = 0;
        const failDetails = [];

        for (const [index, overtime] of overtimeData.entries()) {
          try {
            // 检查是否已存在相同工号和日期的记录
            const existingRecord = this.overtimeData.find(item =>
                item.employeeNumber === overtime.employeeNumber &&
                item.overtimeDate === overtime.overtimeDate
            );

            let result;
            if (existingRecord) {
              // 更新现有记录 - 保留原记录ID
              const updateData = {
                ...existingRecord, // 保留所有原有字段
                ...overtime,      // 用新数据覆盖
                id: existingRecord.id, // 重要：使用原记录ID
                update_time: new Date().toISOString(),
                sys_update_user: this.useName
              };
              result = await this.$request.post('/editOvertimeMonitoring', updateData);
            } else {
              // 添加新记录 - 使用生成的ID
              const insertData = {
                ...overtime,
                creator: this.useName,
                create_time: new Date().toISOString(),
              };
              result = await this.$request.post('/insertOvertimeMonitoring', insertData);
            }

            if (result.code === 200 || result.msg === 'success') {
              successCount++;
            } else {
              failCount++;
              failDetails.push({
                row: index + 2,
                reason: result.msg || '操作失败'
              });
            }
          } catch (error) {
            failCount++;
            failDetails.push({
              row: index + 2,
              reason: '接口调用异常: ' + (error.message || '未知错误')
            });
          }
        }

        this.uploadResult = {
          success: successCount,
          fail: failCount,
          failDetails: failDetails
        };

        if (failCount === 0) {
          this.$message.success(`成功处理 ${successCount} 条数据`);
          this.closeExcelUploadDialog();
          await this.queryAllOvertime();
        } else {
          this.$message.warning(`处理完成，成功 ${successCount} 条，失败 ${failCount} 条`);
        }
      } catch (error) {
        console.error('上传Excel失败:', error);
        this.$message.error('处理Excel文件失败: ' + (error.message || '未知错误'));
      } finally {
        this.uploadLoading = false;
      }
    },

    readExcelFile(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (e) => {
          try {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

            const filteredData = jsonData.filter(row =>
                row.length > 0 && row.some(cell => cell !== null && cell !== '')
            );

            resolve(filteredData);
          } catch (error) {
            reject(error);
          }
        };

        reader.onerror = (error) => reject(error);
        reader.readAsArrayBuffer(file);
      });
    },

    transformExcelData(excelData) {
      if (!excelData || excelData.length < 2) {
        throw new Error('Excel文件格式不正确或没有数据');
      }

      const headers = excelData[0];
      const dataRows = excelData.slice(1);

      // 定义字段映射 - 支持多种可能的表头名称
      const headerMapping = {
        '工号': 'employeeNumber',
        '工号*': 'employeeNumber',
        '员工工号': 'employeeNumber',
        '员工编号': 'employeeNumber',
        '姓名': 'name',
        '姓名*': 'name',
        '员工姓名': 'name',
        '加班日期': 'overtimeDate',
        '加班日期*': 'overtimeDate',
        '日期': 'overtimeDate',
        '加班时长': 'overtimeHour',
        '加班时长(小时)': 'overtimeHour',
        '加班时长(小时)*': 'overtimeHour',
        '时长': 'overtimeHour',
        '部门': 'department',
        '科室': 'section',
        '操作类型': 'operation',
        '加班类别': 'category',
        '加班原因': 'reason'
      };

      // 清理和标准化表头
      const cleanHeaders = headers.map(header => {
        if (typeof header === 'string') {
          // 去除空格和特殊字符
          return header.replace(/\s+/g, '').replace(/\*/g, '');
        }
        return header;
      });

      // 检查必需的字段 - 使用更灵活的方式
      const requiredFields = [
        { keys: ['工号', '员工工号', '员工编号'], field: 'employeeNumber' },
        { keys: ['姓名', '员工姓名'], field: 'name' },
        { keys: ['加班日期', '日期'], field: 'overtimeDate' },
        { keys: ['加班时长', '时长'], field: 'overtimeHour' }
      ];

      const missingHeaders = [];

      requiredFields.forEach(required => {
        const found = cleanHeaders.some(header =>
            required.keys.some(key => header.includes(key))
        );
        if (!found) {
          missingHeaders.push(required.keys[0]);
        }
      });

      if (missingHeaders.length > 0) {
        throw new Error(`Excel文件中缺少必需的列: ${missingHeaders.join(', ')}`);
      }

      // 构建表头映射关系
      const headerMap = {};
      cleanHeaders.forEach((header, index) => {
        // 查找匹配的字段名
        for (const [mapHeader, fieldName] of Object.entries(headerMapping)) {
          const cleanMapHeader = mapHeader.replace(/\s+/g, '').replace(/\*/g, '');
          if (header.includes(cleanMapHeader) || cleanMapHeader.includes(header)) {
            headerMap[fieldName] = index;
            break;
          }
        }
      });

      // 转换数据
      return dataRows.map((row, rowIndex) => {
        const record = {};

        // 使用映射关系提取数据
        Object.entries(headerMap).forEach(([fieldName, columnIndex]) => {
          if (columnIndex >= 0 && columnIndex < row.length) {
            let value = row[columnIndex];

            // 特殊处理数据类型
            if (fieldName === 'overtimeDate' && value) {
              // 处理日期格式
              if (typeof value === 'string') {
                const date = new Date(value);
                if (!isNaN(date.getTime())) {
                  value = date.toISOString().split('T')[0];
                }
              } else if (value instanceof Date) {
                value = value.toISOString().split('T')[0];
              }
            } else if (fieldName === 'overtimeHour' && value) {
              // 处理数字类型
              value = parseFloat(value);
              if (isNaN(value)) {
                throw new Error(`第${rowIndex + 2}行加班时长格式不正确`);
              }
            }

            record[fieldName] = value;
          }
        });

        // 验证必需字段
        if (!record.employeeNumber) {
          throw new Error(`第${rowIndex + 2}行工号不能为空`);
        }
        if (!record.name) {
          throw new Error(`第${rowIndex + 2}行姓名不能为空`);
        }
        if (!record.overtimeDate) {
          throw new Error(`第${rowIndex + 2}行加班日期不能为空`);
        }
        if (!record.overtimeHour && record.overtimeHour !== 0) {
          throw new Error(`第${rowIndex + 2}行加班时长不能为空`);
        }

        // 生成唯一ID - 这里使用时间戳+随机数的方式
        record.id = this.generateUniqueId();

        // 设置默认值
        record.create_time = new Date().toISOString();
        record.update_time = new Date().toISOString();
        record.creator = this.useName;
        record.sys_update_user = this.useName;
        record.sys_deleted = 0;

        return record;
      });
    },
  }
};
</script>

<style scoped>
.el-aside {
  background-color: #f5f7fa;
}

.aside-button {
  width: 100%;
  margin: 5px 0;
  text-align: left;
  border: none;
}

.aside-button:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 40px;
  color: #8c939d;
  margin-bottom: 15px;
}

.el-upload__text {
  color: #8c939d;
  font-size: 14px;
  margin-top: 7px;
}

.headMain {
  cursor: pointer;
  color: white;
}

.headMain:hover {
  text-decoration: underline;
}

.chart-container {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
</style>